<!--实时波动里-->
<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="queryParams" :rules="rules">
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="行情时间">
            <el-input
                v-model="calTime"
                disabled="true"
                size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="计算日期" v-show="false">
            <el-date-picker
                v-model="queryParams.refSetDate"
                type="date"
                value-format="YYYY-MM-DD"
                @change="handleQuery"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="波动率曲面" label-width="80px">
            <el-select v-model="queryParams.vlsCode" placeholder="波动率曲面"
                       size="small"
                       @change="handleQuery"
                       filterable="true" default-first-option
                       :style="{width: '100%'}">
              <el-option
                  v-for="item in vlsCodeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="Search" size="small" style="margin: 3px 3px" @click="handleQuery">搜索
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <xTable ref="curvolcurveRef" refId="curvolcurveRef" multiple="false" :data="vlsDataList"
              @selection-change="handleSelectionChange">
        <template #columList>
          <el-table-column label="期限/行权价" align="center" fixed prop="vls_term_st" width="150"/>
          <el-table-column align="center" width="80" :formatter="formatterPercent"
                           v-for="item in fieldList"
                           :prop="item.key"
                           :label="item.val"
          />
        </template>
      </xTable>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-row style="padding:8px 8px 8px 50px">
          <VolLimitChart height="300px" width="650px" ref="volLimitChart"/>
        </el-row>
        <el-row style="padding:8px 8px 8px 50px">
          <VolPriceChart height="300px" width="650px" ref="volPriceChart"/>
        </el-row>
      </el-col>

      <el-col :span="12">
        <el-row>
          <VolRateSurface ref="volRateSurface" :surfaceChg="volSurfaceChg"/>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="CurVolCurve">

const {proxy} = getCurrentInstance();
import {getVlsCodeList, getRealTimeVlsChartData} from "@/api/curve/volcurve/volcurve";
import VolLimitChart from "../volLimitChart";
import VolPriceChart from "../volPriceChart";
import VolRateSurface from "../volRateSurface";
import xTable from "@/xquant/base/xTable";

const vlsCodeList = ref([]);
const loading = ref(false);
const fieldList = ref([]);
const vlsDataList = ref([]);
const calTime = ref('行情时间: ' + proxy.getCurrTime('YYYY-mm-dd HH:MM:SS', new Date()));
const data = reactive({
  vlsChartData: {},
  form: {},
  queryParams: {
    refSetDate: proxy.getSysDate(),
    // refSetDate:'2021-12-31',
    vlsCode: undefined,
  },
  rules: {
    vlsCode: [{required: true, message: "波动率曲面不能为空", trigger: "blur"}],
  }
});
const interval = ref({});
const {queryParams, form, rules, vlsChartData} = toRefs(data);

/**波动率曲面下拉*/
function getVlsSelectist() {
  getVlsCodeList().then(response => {
    vlsCodeList.value = response.result;
    if (vlsCodeList.value.length > 0) {
      queryParams.value.vlsCode = vlsCodeList.value[0].code;
      handleQuery();
      interval.value = setInterval(function () {
        handleQuery();
      }, 30000);

    }
  })
}

/** 列显示格式化*/
function formatterPercent(row, column, cellValue) {
  return proxy.formartNumber(proxy.lsh.round(cellValue, 4) * 100, 2) + '%';
}

/** 查询列表 */
function getChart() {
  loading.value = true;
  let qryParam = proxy.lsh.cloneDeep(queryParams.value);
  qryParam = proxy.lsh.assign(qryParam, {'refSetTime': proxy.getCurrTime('HH:MM:SS', new Date())});
  getRealTimeVlsChartData(qryParam).then(response => {
    afterDeal(response);
  });
}

function afterDeal(response) {
  if (response != null && response.result != null) {
    calTime.value = response.result.effectTime;
    getGridColumAndData(response.result);
    vlsChartData.value = response;
    let volTitle = '波动率曲面';
    proxy.lsh.map(vlsCodeList.value, function (o) {
      if (o.code == queryParams.value.vlsCode) {
        volTitle = o.name;
      }
    });
    //显示曲线
    proxy.$refs.volLimitChart.setCharData(proxy, '波动率微笑曲线', vlsChartData.value.result, 'vls_strike', 'vls_rate', true);
    proxy.$refs.volPriceChart.setCharData(proxy, '期限结构曲线', vlsChartData.value.result, 'vls_term_st', 'vls_rate', 'vls_strike', true);
    proxy.$refs.volRateSurface.setCharData(proxy, volTitle, vlsChartData.value.result, 'vls_strike', 'vls_term_st', 'vls_rate');
  } else {
    vlsDataList.value = [];
    fieldList.value = [];
    proxy.$modal.alertError(response.errorMsg);
  }
  loading.value = false;
}

/**
 * 处理grid数据
 */
function getGridColumAndData(result) {
  let fields = [];
  let dataMap = new Map();
  let rateMap = new Map();
  let strikeMap = new Map();
  let columnIndex = 0;
  let ratefield = '';
  let strikefield = '';
  const pointLimit = result.pointList;
  const resultList = result.resultList;
  for (var i = 0; i < resultList.length; i++) {
    var term = resultList[i].vls_term_st;
    if (pointLimit.findIndex((v) => {
      return v == resultList[i].vls_term_st
    }) != -1) {
      if (!dataMap.get(term)) {
        dataMap.set(term, {
          vls_term: term,
          vls_term_c: resultList[i].vls_term,
          vls_strike: resultList[i].vls_strike + "",
          vls_code: resultList[i].vls_code,
          vls_term_st: resultList[i].vls_term_st,
        });
      }
      //表头
      var colmntitle;
      //20211119 botao.yu POC讨论结果 将横坐标显示为行权价百分比
      colmntitle = resultList[i].vls_strike;
      colmntitle = proxy.formartNumber(colmntitle, 2) + "%";
      if (!rateMap.get(colmntitle)) {
        columnIndex++;
        ratefield = "rates" + columnIndex;
        strikefield = "strike" + columnIndex;
        rateMap.set(colmntitle, ratefield);
        strikeMap.set(colmntitle, strikefield);
        fields.push({'key': ratefield, 'val': colmntitle});
      }
      dataMap.get(term)[rateMap.get(colmntitle)] = resultList[i].vls_rate;
      dataMap.get(term)[strikeMap.get(colmntitle)] = resultList[i].vls_strike;
    }
  }
  var dataArray = [];
  dataMap.forEach(function (value, key, map) {
    dataArray.push(value);
  });
  fieldList.value = fields;
  vlsDataList.value = dataArray;
}

/** 搜索按钮操作 */
function handleQuery() {
  if (proxy.lsh.isNull(queryParams.value.vlsCode) || queryParams.value.vlsCode == '') {
    fieldList.value = [];
    vlsDataList.value = [];
    proxy.$refs.volLimitChart.clearChart();
    proxy.$refs.volPriceChart.clearChart();
    proxy.$refs.volRateSurface.clearChart();
    return;
  }
  getChart();
}

function volSurfaceChg(params) {
  if (params != undefined && params.length > 0) {
    proxy.$refs.volLimitChart.limitSelectChg(params[1]);
    proxy.$refs.volPriceChart.strikeSelectChg(params[0]);
  }
}

onMounted(() => {
  getVlsSelectist();
})
onDeactivated(() => {
  clearInterval(interval.value);
})


</script>
